import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import AppHeader from '../components/AppHeader';
import PrimaryButton from '../components/PrimaryButton';
import { Colors } from '../constants/colors';
import InputField, { EyeToggle } from '../components/InputField';
import { authService, profileService, AuthManager } from '../services';
import { showError, showSuccess } from '../utils/webAlert';
import { Storage } from '../utils/storage';

export default function EmailLoginScreen() {
  const [email, setEmail] = useState('');
  const [pwd, setPwd] = useState('');
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [rememberPwd, setRememberPwd] = useState(false);
  const nav = useNavigation<any>();

  useEffect(() => {
    const loadSavedCredentials = async () => {
      const savedEmail = await Storage.getItem('saved_email');
      const savedPwd = await Storage.getItem('saved_password');
      
      if (savedEmail && savedPwd) {
        setEmail(savedEmail);
        setPwd(savedPwd);
        setRememberPwd(true);
      }
    };

    loadSavedCredentials();
  }, []);

  // 检查用户认证状态并导航到正确页面
  const checkUserStatusAndNavigate = async () => {
    try {
      const profile = await profileService.getProfile();
      console.log('用户资料:', profile);

      // 如果auditState为null或undefined，说明用户还没有提交认证信息
      if (profile.auditState === null || profile.auditState === undefined) {
        console.log('用户未认证，跳转到认证中心');
        nav.reset({
          index: 0,
          routes: [{ name: 'RoleSelect' }],
        });
      } else {
        // 用户已提交认证信息，正常跳转到主页面
        console.log('用户已认证，跳转到主页面');
        nav.reset({
          index: 0,
          routes: [{ name: 'MainTabs', params: { initialTab: 'Profile' } }],
        });
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
      // 如果获取用户资料失败，也跳转到主页面
      nav.reset({
        index: 0,
        routes: [{ name: 'MainTabs', params: { initialTab: 'Profile' } }],
      });
    }
  };

  const handleLogin = async () => {
    if (!email.trim()) {
      showError('請輸入電郵地址');
      return;
    }

    if (!pwd.trim()) {
      showError('請輸入密碼');
      return;
    }

    // 簡單的電郵格式驗證
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showError('請輸入有效的電郵地址');
      return;
    }

    setLoading(true);
    try {
      const result = await authService.emailPasswordLogin({
        email: email.trim(),
        password: pwd.trim(),
      });
      // 保存token
      if (result.token) {
        await AuthManager.setToken(result.token);
        console.log('Token保存完成:', result.token);
      }

      // 处理记住密码逻辑
      if (rememberPwd) {
        await Storage.setItem('saved_email', email.trim());
        await Storage.setItem('saved_password', pwd.trim());
      } else {
        // 如果取消记住密码，则删除已保存的凭据
        await Storage.removeItem('saved_email');
        await Storage.removeItem('saved_password');
      }

      showSuccess(result.message || '登錄成功', () => {
        // 使用setTimeout确保在Web端也能正确跳转
        setTimeout(() => {
          checkUserStatusAndNavigate();
        }, 100);
      });
    } catch (error: any) {
      console.error('登錄失敗:', error);
      showError(error.message || '請檢查您的電郵和密碼');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <AppHeader title="電郵登錄" showBack variant="plain" largeTitle />

      <View style={styles.content}>
        <View style={{ marginTop: 12 }}>
          <InputField
            label="電郵地址"
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
            autoCapitalize="none"
            variant="card"
          />
        </View>

        <View style={{ marginTop: 12 }}>
          <InputField
            label="密碼"
            value={pwd}
            onChangeText={setPwd}
            secureTextEntry={!showPwd}
            right={<EyeToggle visible={showPwd} onToggle={() => setShowPwd(v => !v)} />}
            variant="card"
          />
        </View>

        <TouchableOpacity 
          style={styles.rememberPwdContainer} 
          onPress={() => setRememberPwd(!rememberPwd)}
        >
          <View style={[
            styles.checkbox, 
            rememberPwd && styles.checkboxChecked
          ]}>
            {rememberPwd && <View style={styles.checkboxInner} />}
          </View>
          <Text style={styles.rememberPwdText}>記住密碼</Text>
        </TouchableOpacity>

        <PrimaryButton
          title={loading ? "登錄中..." : "登錄"}
          onPress={handleLogin}
          disabled={loading}
          style={{ marginTop: 12 }}
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.white },
  content: { padding: 20 },
  label: { color: Colors.gray[400], marginBottom: 8 },
  cardWrap: {
    backgroundColor: Colors.white,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.gray[200],
    padding: 14,
    marginHorizontal: 4,
    marginTop: 16,
    shadowColor: Colors.black,
    shadowOpacity: 0.03,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 2 },
  },
  rememberPwdContainer: {
    flexDirection: 'row', 
    alignItems: 'center', 
    marginTop: 12
  },
  checkbox: {
    width: 20,
    height: 20,
    borderWidth: 2,
    borderColor: Colors.gray[300],
    borderRadius: 4,
    marginRight: 8,
    justifyContent: 'center',
    alignItems: 'center'
  },
  checkboxChecked: {
    backgroundColor: Colors.primary,
    borderColor: Colors.primary
  },
  checkboxInner: {
    width: 10,
    height: 10,
    backgroundColor: Colors.white,
    borderRadius: 2
  },
  rememberPwdText: {
    color: Colors.gray[700]
  }
});

